<!DOCTYPE html>
<html>
<head>
    

    

    



    <meta charset="utf-8">
    
    
    
    <title>PHP cookie 与 session | Xiaoming&#39;s Blog | 一入前端深似海，从此妹子是路人。</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    <meta name="theme-color" content="#3F51B5">
    
    
    <meta name="keywords" content="PHP,cookie,session">
    <meta name="description" content="PHP 脚本在服务器上执行，然后向浏览器发送回纯 HTML 结果。">
<meta name="keywords" content="PHP,cookie,session">
<meta property="og:type" content="article">
<meta property="og:title" content="PHP cookie 与 session">
<meta property="og:url" content="http://www.lovebxm.com/2017/05/30/PHP_Cookie_Session/index.html">
<meta property="og:site_name" content="Xiaoming&#39;s Blog">
<meta property="og:description" content="PHP 脚本在服务器上执行，然后向浏览器发送回纯 HTML 结果。">
<meta property="og:image" content="http://www.runoob.com/wp-content/uploads/2016/04/php-elephant.png">
<meta property="og:image" content="http://oph264zoo.bkt.clouddn.com/17-5-10/54838474-file_1494405764677_36fc.png">
<meta property="og:updated_time" content="2017-05-30T15:47:03.415Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="PHP cookie 与 session">
<meta name="twitter:description" content="PHP 脚本在服务器上执行，然后向浏览器发送回纯 HTML 结果。">
<meta name="twitter:image" content="http://www.runoob.com/wp-content/uploads/2016/04/php-elephant.png">
    
        <link rel="alternate" type="application/atom+xml" title="Xiaoming&#39;s Blog" href="/atom.xml">
    
    <link rel="shortcut icon" href="/favicon.ico">
    <link rel="stylesheet" href="//unpkg.com/hexo-theme-material-indigo@latest/css/style.css">
    <script>window.lazyScripts=[]</script>
</head>

<body>
    <div id="loading" class="active"></div>

    <aside id="menu"  >
  <div class="inner flex-row-vertical">
    <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menu-off">
        <i class="icon icon-lg icon-close"></i>
    </a>
    <div class="brand-wrap" style="background-image:url(/img/brand.jpg)">
      <div class="brand">
        <a href="/" class="avatar waves-effect waves-circle waves-light">
          <img src="/img/avatar.jpg">
        </a>
        <hgroup class="introduce">
          <h5 class="nickname">白小明</h5>
          <a href="mailto:80583600@qq.com" title="80583600@qq.com" class="mail">80583600@qq.com</a>
        </hgroup>
      </div>
    </div>
    <div class="scroll-wrap flex-col">
      <ul class="nav">
        
            <li class="waves-block waves-effect">
              <a href="/"  >
                <i class="icon icon-lg icon-home"></i>
                主页
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/tags"  >
                <i class="icon icon-lg icon-tags"></i>
                标签
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/hand-peace-o"  >
                <i class="icon icon-lg icon-hand-peace-o"></i>
                作品
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="https://github.com/bxm0927" target="_blank" >
                <i class="icon icon-lg icon-github"></i>
                Github
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/user"  >
                <i class="icon icon-lg icon-user"></i>
                关于我
              </a>
            </li>
        
            <li class="waves-block waves-effect">
              <a href="/404.html"  >
                <i class="icon icon-lg icon-link"></i>
                404 测试
              </a>
            </li>
        
      </ul>
    </div>
  </div>
</aside>

    <main id="main">
        <header class="top-header" id="header">
    <div class="flex-row">
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light on" id="menu-toggle">
          <i class="icon icon-lg icon-navicon"></i>
        </a>
        <div class="flex-col header-title ellipsis">PHP cookie 与 session</div>
        
        <div class="search-wrap" id="search-wrap">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="back">
                <i class="icon icon-lg icon-chevron-left"></i>
            </a>
            <input type="text" id="key" class="search-input" autocomplete="off" placeholder="输入感兴趣的关键字">
            <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="search">
                <i class="icon icon-lg icon-search"></i>
            </a>
        </div>
        
        
        <a href="javascript:;" class="header-icon waves-effect waves-circle waves-light" id="menuShare">
            <i class="icon icon-lg icon-share-alt"></i>
        </a>
        
    </div>
</header>
<header class="content-header post-header">

    <div class="container fade-scale">
        <h1 class="title">PHP cookie 与 session</h1>
        <h5 class="subtitle">
            
                <time datetime="2017-05-30T15:41:23.271Z" itemprop="datePublished" class="page-time">
  2017-05-30
</time>


            
        </h5>
    </div>

    


</header>


<div class="container body-wrap">
    
    <aside class="post-widget">
        <nav class="post-toc-wrap" id="post-toc">
            <h4>TOC</h4>
            <ol class="post-toc"><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#PHP-简介"><span class="post-toc-number">1.</span> <span class="post-toc-text">PHP 简介</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#PHP-版本-link"><span class="post-toc-number">2.</span> <span class="post-toc-text">PHP 版本 link</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#查看-PHP-版本"><span class="post-toc-number">2.0.0.1.</span> <span class="post-toc-text">查看 PHP 版本</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#PHP的大版本主要分三支：PHP4-PHP5-PHP6"><span class="post-toc-number">2.0.0.2.</span> <span class="post-toc-text">PHP的大版本主要分三支：PHP4/PHP5/PHP6</span></a></li><li class="post-toc-item post-toc-level-4"><a class="post-toc-link" href="#除了版本号的不同，同一版本号的PHP版本也有区别，并且在选择PHP扩展的时候需要注意。"><span class="post-toc-number">2.0.0.3.</span> <span class="post-toc-text">除了版本号的不同，同一版本号的PHP版本也有区别，并且在选择PHP扩展的时候需要注意。</span></a></li></ol></li></ol></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#PHP-开发工具"><span class="post-toc-number">3.</span> <span class="post-toc-text">PHP 开发工具</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#cookie-简介"><span class="post-toc-number">4.</span> <span class="post-toc-text">cookie 简介</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#setcookie"><span class="post-toc-number">4.1.</span> <span class="post-toc-text">setcookie()</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#setrawcookie"><span class="post-toc-number">4.2.</span> <span class="post-toc-text">setrawcookie()</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#header"><span class="post-toc-number">4.3.</span> <span class="post-toc-text">header()</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#COOKIE"><span class="post-toc-number">4.4.</span> <span class="post-toc-text">$_COOKIE</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#删除-cookie"><span class="post-toc-number">4.5.</span> <span class="post-toc-text">删除 cookie</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#cookie-的有效路径"><span class="post-toc-number">4.6.</span> <span class="post-toc-text">cookie 的有效路径</span></a></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#session与cookie的异同"><span class="post-toc-number">5.</span> <span class="post-toc-text">session与cookie的异同</span></a></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#session-简介"><span class="post-toc-number">6.</span> <span class="post-toc-text">session 简介</span></a><ol class="post-toc-child"><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#session-start"><span class="post-toc-number">6.1.</span> <span class="post-toc-text">session_start()</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#SESSION"><span class="post-toc-number">6.2.</span> <span class="post-toc-text">$_SESSION</span></a></li><li class="post-toc-item post-toc-level-2"><a class="post-toc-link" href="#删除-session"><span class="post-toc-number">6.3.</span> <span class="post-toc-text">删除 session</span></a></li></ol></li><li class="post-toc-item post-toc-level-1"><a class="post-toc-link" href="#存储用户的登录信息-cookie加解密"><span class="post-toc-number">7.</span> <span class="post-toc-text">存储用户的登录信息 - cookie加解密</span></a></li></ol>
        </nav>
    </aside>
    
<article id="post-PHP_Cookie_Session"
  class="post-article article-type-post fade" itemprop="blogPost">

    <div class="post-card">
        <h1 class="post-card-title">PHP cookie 与 session</h1>
        <div class="post-meta">
            <time class="post-time" title="2017-05-30 23:41:23" datetime="2017-05-30T15:41:23.271Z"  itemprop="datePublished">2017-05-30</time>

            


            
<span id="busuanzi_container_page_pv" title="文章总阅读量" style='display:none'>
    <i class="icon icon-eye icon-pr"></i><span id="busuanzi_value_page_pv"></span>
</span>


            

        </div>
        <div class="post-content" id="post-content" itemprop="postContent">
            <blockquote>
<p>PHP 脚本在服务器上执行，然后向浏览器发送回纯 HTML 结果。</p>
</blockquote>
<a id="more"></a>
<h1 id="PHP-简介"><a href="#PHP-简介" class="headerlink" title="PHP 简介"></a>PHP 简介</h1><ul>
<li>PHP 原为 Personal Home Page 的缩写，已经正式更名为 “<strong>PHP: Hypertext Preprocessor</strong>“。注意不是“Hypertext Preprocessor”的缩写，这种将名称放到定义中的写法被称作<strong>递归缩写</strong>。</li>
<li>PHP 是一种==开源的、免费的、跨平台的、面向对象的==服务器端脚本语言</li>
<li>语法吸收了C语言、Java和Perl的特点，主要适用于Web开发领域。</li>
<li>PHP 兼容几乎所有服务器（Apache, IIS 等等）</li>
<li>PHP 支持多种数据库</li>
</ul>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="http://www.runoob.com/wp-content/uploads/2016/04/php-elephant.png" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure>
<h1 id="PHP-版本-link"><a href="#PHP-版本-link" class="headerlink" title="PHP 版本 link"></a>PHP 版本 <a href="http://php.net/ChangeLog-5.php" target="_blank" rel="external">link</a></h1><h4 id="查看-PHP-版本"><a href="#查看-PHP-版本" class="headerlink" title="查看 PHP 版本"></a>查看 PHP 版本</h4><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span></div><div class="line">    phpinfo();</div><div class="line"><span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<h4 id="PHP的大版本主要分三支：PHP4-PHP5-PHP6"><a href="#PHP的大版本主要分三支：PHP4-PHP5-PHP6" class="headerlink" title="PHP的大版本主要分三支：PHP4/PHP5/PHP6"></a>PHP的大版本主要分三支：PHP4/PHP5/PHP6</h4><ul>
<li>其中，PHP4由于太古老、对QQ支持不力已基本被淘汰，请无视PHP4。</li>
<li>PHP6由于基本没有生产线上的应用，还基本只是一款概念产品，很多功能已在PHP5.3.3上实现，所以也不详述，请无视PHP6。</li>
<li>PHP5的版本主要分四支：PHP5.2之前的版本、PHP5.2.X、PHP5.3和日前发布的PHP5.4。<ul>
<li>PHP5.2之前的版本不值得考虑，因为某些功能缺陷或者BUG。</li>
<li>PHP5.4还处于Beta试用的版本号，非稳定版本，请无视PHP5.4。</li>
</ul>
</li>
</ul>
<h4 id="除了版本号的不同，同一版本号的PHP版本也有区别，并且在选择PHP扩展的时候需要注意。"><a href="#除了版本号的不同，同一版本号的PHP版本也有区别，并且在选择PHP扩展的时候需要注意。" class="headerlink" title="除了版本号的不同，同一版本号的PHP版本也有区别，并且在选择PHP扩展的时候需要注意。"></a>除了版本号的不同，同一版本号的PHP版本也有区别，并且在选择PHP扩展的时候需要注意。</h4><ul>
<li>install版：可执行的MSI格式安装包。</li>
<li>ZIP版：解压即可用。和install版无区别。建议选择ZIP版。</li>
<li>DEBUG版：最终用户无需关心。</li>
</ul>
<table>
<thead>
<tr>
<th>版本号</th>
<th>发布时间</th>
<th>内容</th>
</tr>
</thead>
<tbody>
<tr>
<td>PHP 1</td>
<td>1995年</td>
<td>称为 PHP/FI。提供了访客留言本、访客计数器等简单的功能。</td>
</tr>
<tr>
<td>PHP 2</td>
<td>1995年6月8日</td>
<td>称为 PHP/FI。已经有 PHP 的一些雏型，像是类似 Perl的变量命名方式、表单处理功能、以及嵌入到 HTML 中执行的能力。</td>
</tr>
<tr>
<td>PHP 3</td>
<td>1998年6月</td>
<td>更名为PHP：Hypertext Preprocessor。几乎支持所有主流与非主流数据库。</td>
</tr>
<tr>
<td>PHP 4</td>
<td>2000年5月22日</td>
<td>以Zend Engine 1.0为基础，PHP 的核心：Zend Engine</td>
</tr>
<tr>
<td>PHP 5</td>
<td>2004年7月13日</td>
<td>使用了第二代的Zend Engine 2，包含了许多新特色，如强化的面向对象功能</td>
</tr>
<tr>
<td>PHP 5.5.0</td>
<td>2013年6月20日</td>
<td>此版本包含了大量的新功能和bug修复。需要开发者特别注意的一点是不再支持 Windows XP 和 2003 系统。</td>
</tr>
<tr>
<td>PHP 6</td>
<td>开发正在进行中</td>
<td>PHP6由于基本没有生产线上的应用，还基本只是一款概念产品，很多功能已在PHP5.3.3上实现，所以也不详述，请无视PHP6。</td>
</tr>
</tbody>
</table>
<h1 id="PHP-开发工具"><a href="#PHP-开发工具" class="headerlink" title="PHP 开发工具"></a>PHP 开发工具</h1><ul>
<li>Zend Studio：商业版，Zend官方出品，基于eclipse</li>
<li>Eclipse with PDT：免费</li>
<li>Coda：商业版，针对Mac用户</li>
<li>NetBeans：免费，功能强大</li>
<li>PHP Storm：商业版</li>
<li>Aptana Studio：免费</li>
<li>PhpEd：商业版</li>
<li>Komodo IDE/Edit：IDE为商业版，Edit可免费使用</li>
<li>Adobe Dreamweaver：商业版</li>
</ul>
<blockquote>
<p>cookie / session 机制详解：<a href="http://blog.csdn.net/fangaoxin/article/details/6952954" target="_blank" rel="external">http://blog.csdn.net/fangaoxin/article/details/6952954</a></p>
<p>cookie 是<strong>存储在客户端浏览器</strong>中的数据，通过 Cookie 来跟踪与存储用户数据，常用于<strong>识别用户</strong>。</p>
<p>session 是将用户的会话数据<strong>存储在服务端</strong>，没有大小限制。</p>
</blockquote>
<h1 id="cookie-简介"><a href="#cookie-简介" class="headerlink" title="cookie 简介"></a>cookie 简介</h1><p>cookie 是由服务器发送到浏览器的变量。</p>
<p>一般情况下，Cookie通过<strong>HTTP headers</strong>从服务端返回到客户端。多数web程序都支持Cookie的操作，因为Cookie是存在于HTTP的标头之中，所以必须在其他信息输出以前进行设置，类似于header函数的使用限制。</p>
<p>PHP中的Cookie具有非常广泛的使用，经常用来存储用户的登录信息，购物车等，且在使用会话Session时通常使用Cookie来存储会话id来识别用户，Cookie具备有效期，当有效期结束之后，Cookie会自动的从客户端删除。同时为了进行安全控制，Cookie还可以设置域跟路径。<br><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 设置 cookie</span></div><div class="line">setcookie(<span class="string">"myName"</span>, <span class="string">"白小明"</span>, time() + <span class="number">3600</span>);</div><div class="line"><span class="comment">// header("Set-Cookie:myName=白小明");</span></div><div class="line"></div><div class="line"><span class="comment">// 获取 cookie</span></div><div class="line"><span class="keyword">if</span> (<span class="keyword">isset</span>($_COOKIE[<span class="string">"myName"</span>])) &#123;</div><div class="line">    <span class="keyword">echo</span> <span class="string">"Welcome "</span> . $_COOKIE[<span class="string">"myName"</span>] . <span class="string">"!&lt;br&gt;"</span>;</div><div class="line">&#125;</div><div class="line"><span class="keyword">else</span> &#123;</div><div class="line">    <span class="keyword">echo</span> <span class="string">"Welcome guest!&lt;br&gt;"</span>;</div><div class="line">&#125;</div><div class="line">print_r($_COOKIE);</div><div class="line"></div><div class="line"><span class="comment">// 删除 cookie</span></div><div class="line">setcookie(<span class="string">"myName"</span>, <span class="string">""</span>, time() - <span class="number">1</span>);</div><div class="line"><span class="comment">// header("Set-Cookie:myName=白小明; expires=".gmdate('D, d M Y H:i:s \G\M\T', time()-1));</span></div></pre></td></tr></table></figure></p>
<h2 id="setcookie"><a href="#setcookie" class="headerlink" title="setcookie()"></a>setcookie()</h2><p>setcookie() 函数用于设置 cookie。</p>
<p><strong>注释</strong>：setcookie() 函数必须位于 <html> 标签之前。</html></p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">setcookie(<span class="string">"myName"</span>, <span class="string">"白小明"</span>, time() + <span class="number">3600</span>);</div></pre></td></tr></table></figure>
<figure class="image-bubble">
                <div class="img-lightbox">
                    <div class="overlay"></div>
                    <img src="http://oph264zoo.bkt.clouddn.com/17-5-10/54838474-file_1494405764677_36fc.png" alt="" title="">
                </div>
                <div class="image-caption"></div>
            </figure>
<h2 id="setrawcookie"><a href="#setrawcookie" class="headerlink" title="setrawcookie()"></a>setrawcookie()</h2><p>PHP 中还有一个设置 Cookie 的函数 setrawcookie()</p>
<p>在发送 cookie 时，cookie 的值会自动进行 URL 编码，在取回时进行自动解码（为防止 URL 编码，请使用 setrawcookie() 取而代之）。</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">setrawcookie(<span class="string">'cookie_name'</span>, rawurlencode($value), time()+<span class="number">60</span>*<span class="number">60</span>*<span class="number">24</span>*<span class="number">365</span>);</div></pre></td></tr></table></figure>
<h2 id="header"><a href="#header" class="headerlink" title="header()"></a>header()</h2><p>因为Cookie是通过HTTP标头进行设置的，所以也可以直接使用header方法进行设置。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">header(&quot;Set-Cookie:cookie_name=value&quot;);</div></pre></td></tr></table></figure>
<h2 id="COOKIE"><a href="#COOKIE" class="headerlink" title="$_COOKIE"></a>$_COOKIE</h2><p>任何从浏览器发回的Cookie，PHP都会自动的将他存储在 <strong>$_COOKIE</strong> 的全局变量之中，因此我们可以通过 <strong>$_COOKIE[‘key’]</strong> 的形式来读取某个Cookie值。如：可以通过 $_COOKIE[“user”] 来访问名为 “user” 的 cookie 的值。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">echo $_COOKIE[&quot;myName&quot;];</div><div class="line"></div><div class="line">print_r($_COOKIE);</div></pre></td></tr></table></figure>
<h2 id="删除-cookie"><a href="#删除-cookie" class="headerlink" title="删除 cookie"></a>删除 cookie</h2><p>在PHP中删除cookie也是采用 <strong>setcookie</strong> 函数来实现。</p>
<p>原理：将cookie的过期时间设置到当前时间之前，则该cookie会自动失效，也就达到了删除cookie的目的。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">setcookie(&apos;test&apos;, &apos;&apos;, time()-1);</div></pre></td></tr></table></figure></p>
<p>也可以直接通过header来删除cookie。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">header(&quot;Set-Cookie:test=1393832059; expires=&quot;.gmdate(&apos;D, d M Y H:i:s \G\M\T&apos;, time()-1));</div></pre></td></tr></table></figure></p>
<h2 id="cookie-的有效路径"><a href="#cookie-的有效路径" class="headerlink" title="cookie 的有效路径"></a>cookie 的有效路径</h2><p>cookie 中的路径用来控制设置的cookie在哪个路径下有效，默认为’/‘，在所有路径下都有。<br><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 使test在/path以及子路径/path/abc下都有效，但是在根目录下就读取不到test的cookie值。</span></div><div class="line">setcookie(<span class="string">'CookieName'</span>, <span class="string">'CookieValue'</span>, time() + <span class="number">3600</span>, <span class="string">'/path'</span>);</div></pre></td></tr></table></figure></p>
<hr>
<h1 id="session与cookie的异同"><a href="#session与cookie的异同" class="headerlink" title="session与cookie的异同"></a>session与cookie的异同</h1><ol>
<li><p>cookie 不安全，容易被盗用导致cookie欺骗</p>
</li>
<li><p>单个cookie的值最大只能存储4k，每次请求都要进行网络传输，占用带宽</p>
</li>
<li><p>用户信息既可以存储在sessioin中，也可以存储在cookie中，他们之间的差别在于session可以方便的存取多种数据类型，而cookie只支持字符串类型。</p>
</li>
<li><p>对于一些安全性比较高的数据，cookie需要进行格式化与加密存储，而session存储在服务端则安全性较高。</p>
</li>
</ol>
<h1 id="session-简介"><a href="#session-简介" class="headerlink" title="session 简介"></a>session 简介</h1><p>会话信息是临时的，在用户离开网站后将被删除。如果您需要永久储存信息，可以把数据存储在数据库中。</p>
<p>session 的工作机制是：为每个访问者创建一个唯一的 id (UID)，并基于这个 UID 来存储变量。UID 存储在 cookie 中，亦或通过 URL 进行传导。</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div></pre></td><td class="code"><pre><div class="line"><span class="comment">// 启动会话，同时为用户会话分配一个 UID。</span></div><div class="line">session_start();</div><div class="line"></div><div class="line"><span class="comment">// 设置 session</span></div><div class="line"><span class="comment">// $_SESSION['sessionName'] = 'sessionValue';</span></div><div class="line">$_SESSION[<span class="string">'ary'</span>] = <span class="keyword">array</span>(<span class="string">'name'</span> =&gt; <span class="string">'jobs'</span>);</div><div class="line">$_SESSION[<span class="string">'obj'</span>] = <span class="keyword">new</span> stdClass();</div><div class="line"><span class="keyword">echo</span> <span class="string">"session_id:"</span> . session_id() . <span class="string">"&lt;br&gt;"</span>;</div><div class="line"></div><div class="line"><span class="keyword">if</span>(<span class="keyword">isset</span>($_SESSION[<span class="string">'sessionName'</span>]))&#123;</div><div class="line">    $_SESSION[<span class="string">'sessionName'</span>] += <span class="number">1</span>;</div><div class="line">&#125; <span class="keyword">else</span> &#123;</div><div class="line">    $_SESSION[<span class="string">'sessionName'</span>] = <span class="number">1</span>;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">// 获取 session</span></div><div class="line"><span class="keyword">echo</span> <span class="string">"sessionName:"</span> . $_SESSION[<span class="string">'sessionName'</span>];</div><div class="line">var_dump($_SESSION);</div><div class="line"></div><div class="line"><span class="comment">// 删除 session</span></div><div class="line"><span class="keyword">unset</span>($_SESSION[<span class="string">'sessionName'</span>]);</div><div class="line"><span class="keyword">unset</span>($_SESSION[<span class="string">'ary'</span>]);</div><div class="line"><span class="keyword">unset</span>($_SESSION[<span class="string">'obj'</span>]);</div><div class="line"><span class="comment">// session_destroy();</span></div></pre></td></tr></table></figure>
<h2 id="session-start"><a href="#session-start" class="headerlink" title="session_start()"></a>session_start()</h2><p>session_start() 函数用于启动会话，且必须位于 <html> 标签之前。</html></p>
<h2 id="SESSION"><a href="#SESSION" class="headerlink" title="$_SESSION"></a>$_SESSION</h2><p>存储和取回 session 变量的正确方法是使用 $_SESSION 变量</p>
<h2 id="删除-session"><a href="#删除-session" class="headerlink" title="删除 session"></a>删除 session</h2><p>如果您希望删除某些 session 数据，可以使用 unset() 或 session_destroy() 函数。</p>
<ul>
<li><p>unset() 函数用于释放指定的 session 变量，删除某个session值可以使用 unset() 函数</p>
</li>
<li><p>session_destroy() 将重置 session，您将失去所有已存储的 session 数据，如果要删除所有的session，可以使用 session_destroy() 函数，但是 session_id 仍然存在。</p>
</li>
<li><p><strong>注释</strong>：如果需要销毁session_id，通常在用户退出的时候可能会用到，则还需要显式的调用setcookie方法删除session_id的cookie值。</p>
</li>
<li><p><strong>注释</strong>：session_destroy() 并不会立即的销毁全局变量$_SESSION中的值，只有当下次再访问的时候，$_SESSION才为空，因此如果需要立即销毁$_SESSION，可以使用unset函数。</p>
</li>
</ul>
<h1 id="存储用户的登录信息-cookie加解密"><a href="#存储用户的登录信息-cookie加解密" class="headerlink" title="存储用户的登录信息 - cookie加解密"></a>存储用户的登录信息 - cookie加解密</h1><figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div></pre></td><td class="code"><pre><div class="line">session_start();</div><div class="line"></div><div class="line"><span class="comment">//假设用户登录成功获得了以下用户数据</span></div><div class="line">$userinfo = <span class="keyword">array</span>(</div><div class="line">    <span class="string">'uid'</span>  =&gt; <span class="number">10000</span>,</div><div class="line">    <span class="string">'name'</span> =&gt; <span class="string">'spark'</span>,</div><div class="line">    <span class="string">'email'</span> =&gt; <span class="string">'spark@qq.com'</span>,</div><div class="line">    <span class="string">'sex'</span>  =&gt; <span class="string">'man'</span>,</div><div class="line">    <span class="string">'age'</span>  =&gt; <span class="string">'18'</span></div><div class="line">);</div><div class="line"></div><div class="line">header(<span class="string">"content-type:text/html; charset=utf-8"</span>);</div><div class="line"></div><div class="line"><span class="comment">// 将用户信息保存到session中</span></div><div class="line">$_SESSION[<span class="string">'userinfo'</span>] = $userinfo;</div><div class="line">print_r($_SESSION);</div><div class="line"><span class="comment">// 将用户数据保存到cookie中的一个简单方法 -- 加密</span></div><div class="line">$secureKey = <span class="string">'imooc'</span>; <span class="comment">//加密密钥</span></div><div class="line">$str = serialize($userinfo); <span class="comment">//将用户信息序列化</span></div><div class="line">$str = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($secureKey), $str, MCRYPT_MODE_ECB));</div><div class="line"><span class="keyword">echo</span> <span class="string">"加密后的用户信息："</span>;</div><div class="line">print_r($str);</div><div class="line"></div><div class="line"><span class="comment">//将加密后的用户数据存储到cookie中</span></div><div class="line">setcookie(<span class="string">'userinfo'</span>, $str);</div><div class="line"></div><div class="line"><span class="comment">// 当需要使用时进行 -- 解密</span></div><div class="line">$str = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($secureKey), base64_decode($str), MCRYPT_MODE_ECB);</div><div class="line">$uinfo = unserialize($str);</div><div class="line"><span class="keyword">echo</span> <span class="string">"解密后的用户信息："</span>;</div><div class="line">print_r($uinfo);</div></pre></td></tr></table></figure>

        </div>

        <blockquote class="post-copyright">
    <div class="content">
        
<span class="post-time">
    最后更新时间：<time datetime="2017-05-30T15:47:03.415Z" itemprop="dateUpdated">2017-05-30 23:47:03</time>
</span><br>


        
        原始文章链接：<a href="/2017/05/30/PHP_Cookie_Session/" target="_blank" rel="external">http://www.lovebxm.com/2017/05/30/PHP_Cookie_Session/</a>
        
    </div>
    <footer>
        <a href="http://www.lovebxm.com">
            <img src="/img/avatar.jpg" alt="白小明">
            白小明
        </a>
    </footer>
</blockquote>

        
<div class="page-reward">
    <a id="rewardBtn" href="javascript:;" class="page-reward-btn waves-effect waves-circle waves-light">赏</a>
</div>



        <div class="post-footer">
            
	<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/PHP/">PHP</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/cookie/">cookie</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/session/">session</a></li></ul>


            
<div class="page-share-wrap">
    

<div class="page-share" id="pageShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://www.lovebxm.com/2017/05/30/PHP_Cookie_Session/&title=《PHP cookie 与 session》 — Xiaoming's Blog&pic=http://www.lovebxm.com/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://www.lovebxm.com/2017/05/30/PHP_Cookie_Session/&title=《PHP cookie 与 session》 — Xiaoming's Blog&source=
PHP 脚本在服务器上执行，然后向浏览器发送回纯 HTML 结果。
" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://www.lovebxm.com/2017/05/30/PHP_Cookie_Session/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《PHP cookie 与 session》 — Xiaoming's Blog&url=http://www.lovebxm.com/2017/05/30/PHP_Cookie_Session/&via=http://www.lovebxm.com" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://www.lovebxm.com/2017/05/30/PHP_Cookie_Session/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>



    <a href="javascript:;" id="shareFab" class="page-share-fab waves-effect waves-circle">
        <i class="icon icon-share-alt icon-lg"></i>
    </a>
</div>



        </div>
    </div>

    
<nav class="post-nav flex-row flex-justify-between">
  
    <div class="waves-block waves-effect prev">
      <a href="/2017/05/31/RegExp/" id="post-prev" class="post-nav-link">
        <div class="tips"><i class="icon icon-angle-left icon-lg icon-pr"></i> Prev</div>
        <h4 class="title">最全正则表达式总结：验证QQ号、手机号、Email、中文、邮编、身份证、IP地址等</h4>
      </a>
    </div>
  

  
    <div class="waves-block waves-effect next">
      <a href="/2017/05/30/mysqlCommon/" id="post-next" class="post-nav-link">
        <div class="tips">Next <i class="icon icon-angle-right icon-lg icon-pl"></i></div>
        <h4 class="title">MySQL 安装（Windows）及常用命令</h4>
      </a>
    </div>
  
</nav>



    










    <div id="cloud-tie-wrapper" class="comments cloud-tie-wrapper"></div>
    <script>
    var cloudTieConfig = {
        url: 'http://www.lovebxm.com/2017/05/30/PHP_Cookie_Session/index.html',
        sourceId: 'PHP_Cookie_Session',
        productKey: '294c776acae94037bdd6605780e549e4',
        target: 'cloud-tie-wrapper',
        pcFiles: [
            '//unpkg.com/hexo-theme-material-indigo@latest/css/cloudTie/pc.css',
            '//unpkg.com/hexo-theme-material-indigo@latest/js/cloudTie/pc.min.js',
        ],
        mobileFiles: [
            '//unpkg.com/hexo-theme-material-indigo@latest/css/cloudTie/mobile.css',
            '//unpkg.com/hexo-theme-material-indigo@latest/js/cloudTie/mobile.min.js'
        ]
    };
    </script>
    <script src="//unpkg.com/hexo-theme-material-indigo@latest/js/cloudTie/loader.min.js"></script>







</article>

<div id="reward" class="page-modal reward-lay">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <h3 class="reward-title">
        <i class="icon icon-quote-left"></i>
        谢谢您~
        <i class="icon icon-quote-right"></i>
    </h3>
    <ul class="reward-items">
        
        <li>
            <img src="/img/wechat.jpg" title="微信打赏二维码" alt="微信打赏二维码">
            <p>微信</p>
        </li>
        

        
        <li>
            <img src="/img/alipay.jpg" title="支付宝打赏二维码" alt="支付宝打赏二维码">
            <p>支付宝</p>
        </li>
        
    </ul>
</div>



</div>

        <!-- <footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循<a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
        </p>
    </div>
    <div class="bottom">
        <p>
            <span>Power by <a href="http://hexo.io/" target="_blank">Hexo</a> Theme <a href="https://github.com/yscoder/hexo-theme-indigo" target="_blank">indigo</a></span>
            <span>白小明 &copy; 2017</span>
        </p>
    </div>
</footer> -->

<footer class="footer">
    <div class="top">
        
<p>
    <span id="busuanzi_container_site_uv" style='display:none'>
        总访客数：<span id="busuanzi_value_site_uv"></span>
    </span>
    <span id="busuanzi_container_site_pv" style='display:none'>
        总访问量：<span id="busuanzi_value_site_pv"></span>
    </span>
</p>


        <p>
            
                <span><a href="/atom.xml" target="_blank" class="rss" title="rss"><i class="icon icon-lg icon-rss"></i></a></span>
            
            <span>博客内容遵循<a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">知识共享 署名 - 非商业性 - 相同方式共享 4.0 国际协议</a></span>
            <span>白小明 &copy; 2017</span>
        </p>
    </div>
    <div class="bottom">
        <p>
        <span>
        <a target="_blank" href="mailto:80583600@qq.com" style="border-bottom:none">
        <img src="" alt="E-mail 联系" style="width:20px;height:20px;border:none;">
        </a>
        </span>

        <span>
        <a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin=80583600&site=qq&menu=yes" style="border-bottom:none">
        <img src="" title="QQ 联系" style="width:22px;height:22px;border:none;"></a>
        </span>

        <span>
        <a target="_blank" href="https://github.com/bxm0927" style="border-bottom:none">
        <img src="" alt="GitHub microzz" title="GitHub 联系" style="width:19px;height:19px;border:none;"></a>
        </span>
        </p>
    </div>
</footer>




    </main>
    <div class="mask" id="mask"></div>
<a href="javascript:;" id="gotop" class="waves-effect waves-circle waves-light"><span class="icon icon-lg icon-chevron-up"></span></a>



<div class="global-share" id="globalShare">
    <ul class="reset share-icons">
      <li>
        <a class="weibo share-sns" target="_blank" href="http://service.weibo.com/share/share.php?url=http://www.lovebxm.com/2017/05/30/PHP_Cookie_Session/&title=《PHP cookie 与 session》 — Xiaoming's Blog&pic=http://www.lovebxm.com/img/avatar.jpg" data-title="微博">
          <i class="icon icon-weibo"></i>
        </a>
      </li>
      <li>
        <a class="weixin share-sns wxFab" href="javascript:;" data-title="微信">
          <i class="icon icon-weixin"></i>
        </a>
      </li>
      <li>
        <a class="qq share-sns" target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=http://www.lovebxm.com/2017/05/30/PHP_Cookie_Session/&title=《PHP cookie 与 session》 — Xiaoming's Blog&source=
PHP 脚本在服务器上执行，然后向浏览器发送回纯 HTML 结果。
" data-title=" QQ">
          <i class="icon icon-qq"></i>
        </a>
      </li>
      <li>
        <a class="facebook share-sns" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://www.lovebxm.com/2017/05/30/PHP_Cookie_Session/" data-title=" Facebook">
          <i class="icon icon-facebook"></i>
        </a>
      </li>
      <li>
        <a class="twitter share-sns" target="_blank" href="https://twitter.com/intent/tweet?text=《PHP cookie 与 session》 — Xiaoming's Blog&url=http://www.lovebxm.com/2017/05/30/PHP_Cookie_Session/&via=http://www.lovebxm.com" data-title=" Twitter">
          <i class="icon icon-twitter"></i>
        </a>
      </li>
      <li>
        <a class="google share-sns" target="_blank" href="https://plus.google.com/share?url=http://www.lovebxm.com/2017/05/30/PHP_Cookie_Session/" data-title=" Google+">
          <i class="icon icon-google-plus"></i>
        </a>
      </li>
    </ul>
 </div>


<div class="page-modal wx-share" id="wxShare">
    <a class="close" href="javascript:;"><i class="icon icon-close"></i></a>
    <p>扫一扫，分享到微信</p>
    <img src="" alt="微信分享二维码">
</div>




    <script src="//cdn.bootcss.com/node-waves/0.7.4/waves.min.js"></script>
<script>
var BLOG = { ROOT: '/', SHARE: true, REWARD: true };



</script>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/main.min.js"></script>


<div class="search-panel" id="search-panel">
    <ul class="search-result" id="search-result"></ul>
</div>
<template id="search-tpl">
<li class="item">
    <a href="{path}" class="waves-block waves-effect">
        <div class="title ellipsis" title="{title}">{title}</div>
        <div class="flex-row flex-middle">
            <div class="tags ellipsis">
                {tags}
            </div>
            <time class="flex-col time">{date}</time>
        </div>
    </a>
</li>
</template>

<script src="//unpkg.com/hexo-theme-material-indigo@latest/js/search.min.js" async></script>






<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>



<script>
(function() {
    var OriginTitile = document.title, titleTime;
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            document.title = '死鬼去哪里了！';
            clearTimeout(titleTime);
        } else {
            document.title = '(つェ⊂)咦!又好了!';
            titleTime = setTimeout(function() {
                document.title = OriginTitile;
            },2000);
        }
    });
})();
</script>



</body>
</html>
